// src/composables/useCareerAI.js
import { ref, computed } from 'vue'
import careerData from '../../public/data/career-data.json'

export function useCareerAI() {

  console.log('Loaded Career Data:', careerData) // 打印加载的 JSON 数据

  // 响应式数据
  const city = ref('')
  const career = ref('')
  const minSalary = ref(8000)
  const maxSalary = ref(20000)
  const mode = ref('searchByCareer')
  const isLoading = ref(false)
  const error = ref(null)

  // 智能推荐算法
  const recommendations = computed(() => {
    if (!city.value) return []
    
    if (mode.value === 'searchByCareer') {
      return findCareerData()
    } else {
      return matchCareersBySalary()
    }
  })

  // 职业查询算法
  const findCareerData = () => {
    try {
      const careers = careerData[city.value] || {}
      const lowerCareer = career.value.toLowerCase()
      
      // 模糊匹配算法
      const matched = Object.entries(careers)
        .filter(([key]) => key.toLowerCase().includes(lowerCareer))
        .map(([title, data]) => ({
          title,
          ...data,
          matchScore: calculateMatchScore(title, data)
        }))
        .sort((a, b) => b.matchScore - a.matchScore)

      return matched.slice(0, 5)
    } catch (err) {
      error.value = '查询职业数据时出错'
      return []
    }
  }

  // 薪资匹配算法
  const matchCareersBySalary = () => {
    try {
      const careers = careerData[city.value] || {}
      return Object.entries(careers)
        .filter(([_, data]) => data.avgSalary >= minSalary.value && data.avgSalary <= maxSalary.value)
        .map(([title, data]) => ({
          title,
          ...data,
          compositeScore: (data.avgSalary * 0.6) + (data.employmentRate * 10000 * 0.4)
        }))
        .sort((a, b) => b.compositeScore - a.compositeScore)
        .slice(0, 5)
    } catch (err) {
      error.value = '匹配薪资数据时出错'
      return []
    }
  }

  // 智能匹配评分算法
  const calculateMatchScore = (title, data) => {
    const titleSimilarity = title.includes(career.value) ? 1 : 0.7
    const salaryWeight = data.avgSalary / 20000
    const employmentWeight = data.employmentRate
    return (titleSimilarity * 0.5) + (salaryWeight * 0.3) + (employmentWeight * 0.2)
  }

  // 获取推荐
  const getRecommendations = async () => {
    if (!city.value) {
      error.value = '请先输入城市'
      return
    }
    
    if (mode.value === 'searchByCareer' && !career.value) {
      error.value = '请先输入职业名称'
      return
    }

    if (mode.value === 'searchBySalary' && minSalary.value > maxSalary.value) {
      error.value = '最低薪资不能高于最高薪资'
      return
    }

    isLoading.value = true
    error.value = null
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 800))
    
    isLoading.value = false
  }

  return {
    city,
    career,
    minSalary,
    maxSalary,
    mode,
    recommendations,
    isLoading,
    error,
    getRecommendations
  }
}